package adminorg;


import com.vaadin.data.Container;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.ui.*;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Window.Notification;

import adminorg.DatabaseHelper;
import com.oros.db.*;
//import adminorg.db.AETableContainer;

import de.rac.vaadin.framework.ui.ConfirmDialog;
import de.rac.vaadin.framework.ui.ResourcePool;


public class BPAdminForm extends VerticalLayout {


	private static final long serialVersionUID = 7585826489324450967L;

	private VerticalLayout vertLeft,vertRight;
	//private DatabaseHelper dbHelp;
	private BPObjectWindow bpObjectWindow;
	private BPTaskWindow bpTaskWindow;
	private BPPostWindow bpPostWindow;
	private BPDocumentWindow bpDocumentWindow;
	private HorizontalLayout mainLayout;
	private ComboBox CompCombo;
	public BPAdminForm(DatabaseHelper dbHelp) throws Exception
	{
		//this.dbHelp = dbHelp;
		this.setWidth("100%");
		mainLayout = new HorizontalLayout();
		//DictLayout.setSizeFull();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		CompCombo = DefaultWindow.getCompanyComboBox(dbHelp,mainLayout,new DefaultWindow.newCompanyEvent() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void notifyOfNewCompany(Integer id) {
				// TODO Auto-generated method stub
				if (bpDocumentWindow!=null) bpDocumentWindow.notifyOfCompanyChange();
				if (bpPostWindow!=null) bpPostWindow.notifyOfCompanyChange();
				if (bpTaskWindow!=null) bpTaskWindow.notifyOfCompanyChange();
				if (bpObjectWindow!=null) bpObjectWindow.notifyOfCompanyChange();
			}
		});
		
		this.addComponent(CompCombo);
		this.addComponent(mainLayout);
		this.setComponentAlignment(CompCombo,  Alignment.TOP_RIGHT);
		this.setComponentAlignment(mainLayout,  Alignment.TOP_LEFT);
		vertLeft = new VerticalLayout();
		vertLeft.setWidth("100%");
		vertLeft.setHeight("100%");
		vertRight = new VerticalLayout();
		vertRight.setWidth("100%");
		vertRight.setHeight("100%");
		mainLayout.addComponent(vertLeft);
		mainLayout.addComponent(vertRight);
		mainLayout.setExpandRatio(vertLeft, 66.7f);
		mainLayout.setExpandRatio(vertRight, 33.3f);
		bpObjectWindow = new BPObjectWindow(dbHelp);
		bpTaskWindow = new BPTaskWindow(dbHelp);
		bpPostWindow = new BPPostWindow(dbHelp);
		bpDocumentWindow = new BPDocumentWindow(dbHelp);
		vertLeft.addComponent(bpObjectWindow);
		vertLeft.addComponent(bpTaskWindow);
		vertRight.addComponent(bpPostWindow);
		vertRight.addComponent(bpDocumentWindow);
		bpObjectWindow.activate();
		bpTaskWindow.activate();
        bpPostWindow.activate();
        bpDocumentWindow.activate();
	}
	public Component getBPAdminForm(){
		return this;
	}

	class BPObjectWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = -4319317205175610795L;
        BPObjectWindow(DatabaseHelper dbHelp)
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPObject",
					"EditingBPObject","NoBPObjectRecordIsChosen","BPObjectDeleting",
					"BPObjectRecordWillBeRemoved","BPObjectCodeMustBeUnique");
		}
        @Override
	    public boolean isEditFormDetached()
	    {
	         return true;
	    }
		@Override
		public AETableContainer viewTableInit() throws Exception {
             container = new AEViewContainer("EditBPObject",new AETableContainer[]{dbHelp.getBPObjectContainer(),
            		 dbHelp.getBPEventContainer(),dbHelp.getOrgschemaReadContainer()},
            		 new boolean[]{false,true,true},new String[]{"bpobject.event","bpobject.post"},new int[]
            				 {0,1},null,new String[]{"code"},null,null,null,null);
            
             addSimpleEditFormField("bpobject.code","Code",true);
             addSimpleEditFormField("bpobject.name","Name_NotPerson",true);
             addSimpleEditFormField("bpobject.description","Description",false);
             addTableListEditFormField("bpobject.event","Event",true,"bpevent(name)");
             addTableListEditFormField("bpobject.post","Post",false,"orgschema(post_name)");
             setLikeFilterAsAllMiddleCaseInsensitive();
             return container;
		}

		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"Code","Name_NotPerson","Description","Event","Post"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"bpobject.code","bpobject.name","bpobject.description","bpevent.name","orgschema.post_name"};
		}
		@Override
		protected void containerNewItemSelection(AERawItem item,Object itemId)
		{
		    Object primKey=item.getPrimaryColumnValue();
		    bpTaskWindow.setBPParent(primKey);
		    bpPostWindow.setBPParent(BPPostWindow.BP_PARENT_OBJECT, primKey);
		    bpDocumentWindow.setBPParent(BPDocumentWindow.BP_PARENT_OBJECT, primKey);
		}
		@Override
		protected void containerClickItemEvent(AERawItem item,String columnName)
		{
			containerNewItemSelection(item,item);	
		}
	    @Override
	    public String getDesignEditFormDetachedHeight()
	    {
	          return "350px";
	    }		
	}
	class BPTaskWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = 1L;
         BPTaskWindow(DatabaseHelper dbHelp)
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPTask",
					"EditingBPTask","NoBPTaskRecordIsChosen","BPTaskDeleting",
					"BPTaskRecordWillBeRemoved",null);
		}
        @Override
	    public boolean isEditFormDetached()
	    {
	         return true;
	    }
		@Override
		public AETableContainer viewTableInit() throws Exception {
			 addGeneratedDataListFieldToSpecificContainer("kind",
            		 "Order,Report,CompletionReport,Development",0,"bptasktype","kind_list");
             container = new AEViewContainer("EditBPTask",new AETableContainer[]{dbHelp.getBPTaskContainer(),
            		 dbHelp.getBPObjectContainer(),
            		 dbHelp.getBPPriorityContainer(),dbHelp.getBPTaskTypeContainer()},
            		 new boolean[]{false,true,true,true},
            		 new String[]{"bptask.bp","bptask.priority","bptask.tasktype"},
            		 null,null,new String[]{"bptask.code"},null,null,null,null);
             addSimpleEditFormField("bptask.code","Code",true);
             addSimpleEditFormField("bptask.active","Active",false);
             addSimpleEditFormField("bptask.name","Name_NotPerson",true);
             addSimpleEditFormField("bptask.description","Description",false);
             addDateTimeEditFormField("bptask.time","Time",false,"vvv-HH:mm",false);
             addDateTimeEditFormField("bptask.deadline","Deadline",false,"dd.MM.yyyy hh:mm",true);
             addTableListEditFormField("bptask.priority","Priority",true,"bppriority(name)");
             addTableListEditFormField("bptask.tasktype","TaskType",true,"bptasktype(kind_list)");
             //setLikeFilterAsAllMiddleCaseInsensitive();
             return container;
		}
        public void setBPParent(Object itemId)
        {
        	if (this.viewTable==null) return;
        	if (AETableContainer.isZeroId(itemId)) 
        	{
        		this.viewTable.setVisible(false);
        		return;
        	}
        	if (!this.viewTable.isVisible()) this.viewTable.setVisible(true);
        	container.addEqualContainerFilterColumnAndValue("bptask.bp", itemId);
        	//container.showSourceDetailedInfo(AETableContainer.SHOW_INFO_FULL_ROW);
           	this.viewTable.setValue(null);
        }

		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"BPObject","Code","Active","Name_NotPerson",
					"Description","Time","Deadline","Priority","TaskType"});
			
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"bpobject.name","bptask.code","bptask.active","bptask.name",
					"bptask.description","generated.bptask.time","generated.bptask.deadline",
					"bppriority.name","bptasktype.kind_list"};
		}
		@Override
		protected void containerNewItemSelection(AERawItem item,Object itemId)
		{
		    Object primKey=item.getPrimaryColumnValue();
		    bpPostWindow.setBPParent(BPPostWindow.BP_PARENT_TASK, primKey);
		    bpDocumentWindow.setBPParent(BPDocumentWindow.BP_PARENT_TASK, primKey);
		}
		@Override
		protected void containerClickItemEvent(AERawItem item,String columnName)
		{
			containerNewItemSelection(item,item);	
		}
		public String getDesignEditFormDetachedHeight()
	    {
	          return "450px";
	    }
  	}	
	
	class BPPostWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = -4319317205175610795L;
     	public static final int BP_PARENT_OBJECT=0;
     	public static final int BP_PARENT_TASK=1;
     	private int currentBpParentKind;
     	private Object currentBpParentItemId;
     	private String currentBpParentColumn;
     	private Container.Filter filter;
        BPPostWindow(DatabaseHelper dbHelp)
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPPost",
					"EditingBPPost","NoBPPost","BPPostDeleting",
					"BPPostRecordWillBeRemoved","BPPostCodeMustBeUnique");
		}
        @Override
	    public boolean isEditFormDetached()
	    {
	         return true;
	    }
		@Override
		public void notifyOfCompanyChange()
		{
			currentBpParentItemId=null;
			super.notifyOfCompanyChange();
		}
        public void setBPParent(int parentKind,Object itemId)
        {
        	if (AETableContainer.isZeroId(itemId) || container==null) return;
        	if (parentKind!=currentBpParentKind || currentBpParentItemId==null
        			|| !currentBpParentItemId.equals(itemId))
        	{
        		currentBpParentKind = parentKind;
        		currentBpParentItemId = itemId;
        		currentBpParentColumn = parentKind==BP_PARENT_OBJECT?"bppost.bp":"bppost.task";
        		if (filter!=null) container.removeContainerFilter(filter);
        		filter = new Compare.Equal(currentBpParentColumn, itemId);
        		container.addContainerFilter(filter);
        		ensureDisableFormPanel();
        	}
        }
        @Override
        public boolean isFormReadyForNewEditDelete()
        {
            return currentBpParentItemId!=null;
        }
        @Override
        protected Object createNewRowItem(AETableContainer table) throws Exception
		{
        	Object id = super.createNewRowItem(table);
        	setNewEditItemField(currentBpParentColumn,currentBpParentItemId);
        	return id;
		}
		@Override
		public AETableContainer viewTableInit() throws Exception {
             container = new AEViewContainer("EditBPPost",new AETableContainer[]{dbHelp.getBPPostContainer(),
            		 dbHelp.getOrgschemaReadContainer(),dbHelp.getBPObjectContainer(),dbHelp.getBPTaskContainer()},
            		 new boolean[]{false,true,true,true},new String[]{"bppost.post","bppost.bp","bppost.task"},
            		 new int[]{0,1,1},null,new String[]{"bppost.code"},null,null,null,null);
            
             addSimpleEditFormField("bppost.code","Code",true);
             addTableListEditFormField("bppost.post","Post",true,"orgschema(post_name)");
             addSimpleEditFormField("bppost.verifying","Verifying",true);
             //setLikeFilterAsAllMiddleCaseInsensitive();
             return container;
		}

		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"Code","BPObject","Task","Post","Verifying"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"bppost.code","bpobject.name","bptask.name","orgschema.post_name","bppost.verifying"};
		}
		
	}
	class BPDocumentWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = 1L;
       	public static final int BP_PARENT_OBJECT=0;
     	public static final int BP_PARENT_TASK=1;
     	private int currentBpParentKind;
     	private Object currentBpParentItemId;
     	private String currentBpParentColumn;
     	private Container.Filter filter;
        BPDocumentWindow(DatabaseHelper dbHelp)
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPDocument",
					"EditingBPDocument","NoBPDocumentRecordIsChosen","BPDocumentDeleting",
					"BPDocumentRecordWillBeRemoved",null);
		}
        @Override
	    public boolean isEditFormDetached()
	    {
	         return true;
	    }
        @Override
        public boolean isFormReadyForNewEditDelete()
        {
            return currentBpParentItemId!=null;
        }
		@Override
		public void notifyOfCompanyChange()
		{
			currentBpParentItemId=null;
			super.notifyOfCompanyChange();
		}
		@Override
		public AETableContainer viewTableInit() throws Exception {
             container = new AEViewContainer("EditBPDocument",new AETableContainer[]{dbHelp.getBPDocumentContainer(),
            		 dbHelp.getDocumentContainer(),dbHelp.getBPObjectContainer(),dbHelp.getBPTaskContainer()},
            		 new boolean[]{false,true,true,true},new String[]{"bpdocument.docid","bpdocument.bp","bpdocument.task"},
            		 new int[]{0,1,1},null,new String[]{"documents.name_doc"},null,null,null,null);
             
             //setLikeFilterAsAllMiddleCaseInsensitive();
             return container;
		}
        public void setBPParent(int parentKind,Object itemId)
        {
        	if (AETableContainer.isZeroId(itemId) || container==null) {  return;}
        	if (parentKind!=currentBpParentKind || currentBpParentItemId==null
        			|| !currentBpParentItemId.equals(itemId))
        	{
        		currentBpParentKind = parentKind;
        		currentBpParentItemId = itemId;
        		currentBpParentColumn = parentKind==BP_PARENT_OBJECT?"bpdocument.bp":"bpdocument.task";
        		if (filter!=null) container.removeContainerFilter(filter);
        		filter = new Compare.Equal(currentBpParentColumn, itemId);
        		container.addContainerFilter(filter);
        		ensureDisableFormPanel();
        	}
        }
		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"BPObject","Task","Document"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"bpobject.name","bptask.name","documents.name_doc"};
		}
		@Override
		protected void addMenuBarItemsAtBeginning()
		{
		     menuBar.addItem(dbHelp.getWords("Add"), new MenuBar.Command() {
				
				private static final long serialVersionUID = 1L;

				@Override
				public void menuSelected(MenuItem selectedItem) {
					final DocumentForm docform =((AdminorgApplication)dbHelp.getApplication()).getDocumentForm();
					Component detachableDoc = docform.detachMainLayout();
					getWindow().addWindow(new ConfirmDialog(dbHelp.getWords("DocumentSelection"),
							detachableDoc,
	            			dbHelp.getWords("SelectDocument"),
	            			dbHelp.getWords("Cancel"),
	            			new ConfirmDialog.Callback() {
								
								private static final long serialVersionUID = 50538170833511190L;

								@Override
								public void onDialogResult(boolean resultIsYes) {
									
									if (resultIsYes){
						                
										try {
											Integer docid = docform.getCurrentDocSelection();
											AEViewContainer container = (AEViewContainer)sourceData.getViewTable();
											Object[] tableId = new Object[]{null,docid,(currentBpParentKind==BP_PARENT_OBJECT?currentBpParentItemId:0),
													(currentBpParentKind==BP_PARENT_TASK?currentBpParentItemId:0)};
											AEHelper.logArray(tableId, "Added document item to "+container);
											container.addItem(tableId, null, null);
											sourceData.getViewTable().commit();
						                } catch (Exception e) {
						                	e.printStackTrace();
						                	getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
						                }
										
									}
									docform.reattachMainLayout();
								}

								@Override
								public boolean validateFinish() {
									Integer docid = docform.getCurrentDocSelection();
									if (docid==null)
									{
										getWindow().showNotification(dbHelp.getWords("PleaseSelectTheDocumentOrCancelThisOperation"), Notification.TYPE_ERROR_MESSAGE);
									    return false;
									}
									return true;
								}
							},"1080px","500px"
	            		));
					// end of menu item add
					
				}
			}); 	
		}
	}	
}
